import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ImageBackground,
    RefreshControl,
    ScrollView
} from 'react-native';
import {Stack, useRouter, useLocalSearchParams} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useState} from "react";
import QRCode from 'react-native-qrcode-svg';

import ticketBg from "@/assets/images/order/ticket_bg.png";
import dateTimeIcon from "@/assets/images/collection/dateTime.png";
import addressIcon from "@/assets/images/collection/address.png";
import { getOrderDetailByOrderNum } from "@/services/orederServices"
import {format, isSameDay, parse} from "date-fns/index";



export default function TicketScreen() {

    const router = useRouter();
    const routerParams = useLocalSearchParams();
    const [orderDetail, setOrderDetail] = useState({});

    useEffect(() => {
        getOrderDetailByOrderNum(routerParams.orderNum)
            .then(res => {
                setOrderDetail(res.data);
                console.log('res', res);
            })
            .catch(err => {
                console.log('err', err);
            })
    }, [])

    const handleDate = function (durationStartTime, durationEndTime) {
        if (!durationStartTime) return ;
        if (!durationEndTime) return ;
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        // 解析输入的时间
        const startTime = parse(durationStartTime, 'yyyy-MM-dd HH:mm:ss', new Date());
        const endTime = parse(durationEndTime, 'yyyy-MM-dd HH:mm:ss', new Date());

        // 获取中文星期
        const startWeekday = weekDays[startTime.getDay()];
        const endWeekday = weekDays[endTime.getDay()];

        // 格式化时间
        const startFormatted = format(startTime, `MM.dd 周${startWeekday} HH:mm`);
        const endFormatted = format(endTime, `MM.dd 周${endWeekday} HH:mm`);

        // 判断是否为同一天
        if (isSameDay(startTime, endTime)) {
            return `${startFormatted}-${endFormatted}`;
        } else {
            // 如果不是同一天，按要求的格式输出
            const startDay = format(startTime, 'MM.dd');
            const endDay = format(endTime, 'MM.dd');
            const startTimeOnly = format(startTime, 'HH:mm');
            const endTimeOnly = format(endTime, 'HH:mm');
            return `${startDay} 周${startWeekday} ${startTimeOnly}-${endDay} 周${endWeekday} ${endTimeOnly}`;
        }
    };

    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '凭证', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <ScrollView
                // refreshControl={
                //     <RefreshControl
                //         colors={['#CCC']} // 设置下拉刷新控件的颜色
                //         progressBackgroundColor="#ffffff" // 设置进度条的背景颜色
                //     />
                // }
            >
                <View>
                    <ImageBackground source={ticketBg} style={styles.tickeContainer}>
                        <View>
                            <View>
                                <Text style={styles.ticketTitle}>
                                    { orderDetail?.activityTitle }
                                </Text>
                            </View>
                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ handleDate(orderDetail?.durationStartTime, orderDetail?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>{ orderDetail?.destName }</Text>
                            </View>
                            <View style={styles.ticketNumber}>
                                <Text style={styles.ticketNumberText}>凭证号：{ orderDetail?.orderNum }</Text>
                            </View>
                            <View style={{  flex : 1, margin: "auto", marginTop: 18}}>
                                <QRCode
                                    value="https://example.com"  // 你想要编码的内容
                                    size={scaleSize(165)}                    // 二维码的大小
                                    color="black"                 // 二维码的颜色
                                    backgroundColor="white"       // 二维码的背景颜色
                                />
                            </View>
                        </View>
                    </ImageBackground>
                    <View style={styles.ticketInfoContainer}>
                        <View style={styles.ticketInfoWarp}>
                            <Text style={styles.ticketOne}>票种：{ orderDetail?.ticketName }</Text>
                            <Text style={styles.ticketTwo}>票价：{ orderDetail?.price }</Text>
                        </View>
                        <View style={styles.ticketInfoWarp}>
                            <Text style={styles.ticketOne}>状态：{ orderDetail?.payStatus ? "已支付" : "未支付" }</Text>
                            <Text style={styles.ticketTwo}>实付金额：{ orderDetail?.amount }</Text>
                        </View>
                        <View style={styles.dateTimeInfo}>
                            <Text style={styles.dateTimeInfoText}>有效期：{ orderDetail?.validStartTime && format(orderDetail?.validStartTime, "yyyy/MM/dd") } - { orderDetail?.validEndTime && format(orderDetail?.validEndTime, "yyyy/MM/dd") }</Text>
                        </View>
                        <View style={styles.ticketDesttion}>
                            <Text style={styles.ticketDesttionText}>凭证说明：{ orderDetail?.description || "无" }</Text>
                        </View>
                    </View>
                    <View style={styles.ticketTip}>
                        <Text style={styles.ticketTipTitle}>
                            温馨提示
                        </Text>
                        <View>
                            <Text style={styles.ticketTipContent}>
                                1:请不要把电子票随意分享给他人，以免被盗用
                            </Text>
                            <Text style={styles.ticketTipContent}>
                                2:入场时,请提前打开电子票,调亮手机屏幕,扫描二维码检票 入场，1人1票
                            </Text>
                        </View>
                    </View>
                </View>
            </ScrollView>

        </View>

    );
}

const styles = StyleSheet.create({
    tickeContainer: {
        height: scaleSize(347),
        width: scaleSize(351),
        marginLeft: 12,
        marginRight: 12,
        padding: 16,
    },
    ticketTitle: {
        fontSize: 14,
        fontWeight: "bold",
        color: "#2A2B30",
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 10,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 4,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 4,
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 4,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    ticketNumber: {
        marginTop: 43,
    },
    ticketNumberText: {
        textAlign:"center",
        color: "#2A2B30",
        fontSize: 12,
        letterSpacing: 1,
    },
    ticketInfoWarp: {
        flexDirection: "row",
        marginBottom: 18,
    },
    ticketInfoContainer: {
        padding: 18,
        marginLeft: 12,
        marginRight: 12,
        backgroundColor: "#fff",
        borderRadius: 10,
        marginTop: 12,
    },
    ticketOne: {
        width: 187,
        color: "#2A2B30",
        fontSize: 12,
        letterSpacing: 0.4
    },
    ticketTwo: {
        color: "#2A2B30",
        fontSize: 12,
    },
    dateTimeInfo: {
        marginBottom: 18,
    },
    dateTimeInfoText: {
        color: "#ED2A20",
        fontSize: 12,
        letterSpacing: 0.7,
    },
    ticketDesttion: {

    },
    ticketDesttionText: {
        color: "#2A2B30",
        fontSize: 12,
    },
    ticketTip: {
        marginLeft: 12,
        marginRight: 12,
        marginTop: 12,
        padding: 18,
        backgroundColor: '#fff',
        borderRadius: 10,
    },
    ticketTipTitle: {
        fontWeight: "bold",
        fontSize: 12,
        marginBottom: 10,
    },
    ticketTipContent: {
        color: "#9C9EAC",
        fontSize: 12,
        marginBottom: 3,
    },
});
